package main

import (
	"fmt"
	"im/internal"
	"im/internal/socketIO"
	"im/pkg/databases"
	"im/pkg/logger"
	"log"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "im/docs"
)

// @title Instant Messaging API
// @version 1.0
// @description I'M 即使通讯系统
// @termsOfService https://www.swagger.io/terms/

// @contact.name socket.io
// @contact.url https://socket.io/zh-CN/

// @host 192.168.2.13:8080
// @BasePath /
func main() {
	//退出前关闭数据库连接
	defer databases.DeferClose()
	//读取配置文件
	viper.SetConfigFile("config.yaml")
	//viper.SetConfigFile("config.home.yaml")

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("read configuration failed: %v", err)
	}

	//初始化socket.io
	socketIO.Init(viper.GetString("socket.host"), viper.GetInt("socket.port"))
	//创建gin
	mode := viper.GetString("mode")
	if mode != "" {
		gin.SetMode(mode)
	}
	router := gin.Default()
	_ = router.SetTrustedProxies([]string{fmt.Sprintf("%s:%d", viper.GetString("host"), viper.GetInt("port"))})
	router.Static("/assets", "./assets")
	router.StaticFile("/favicon.ico", "./assets/favicon.ico")
	router.LoadHTMLGlob("templates/**/*")

	//注册swagger
	router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	//建立路由
	internal.InitRouter(router)

	logger.Info(fmt.Sprintf("项目于 %s 在 %s:%d 上启动服务", time.Now().Format("06-01-02 15:04:05"), viper.GetString("host"), viper.GetInt("port")))
	// 监听并在 0.0.0.0:8080 上启动服务
	_ = router.Run(fmt.Sprintf("%s:%d", viper.GetString("host"), viper.GetInt("port")))
}
